<template>
  <div class="flex items-center justify-center h-screen">
    <div
      class="chat-box"
      ref="chatBox"
      @mousedown="startDrag"
      @mouseup="stopDrag"
      @mouseleave="stopDrag"
    >
      <div
        class="header p-2 cursor-move bg-gray-200 rounded-t-lg"
        style="display: flex"
      >
        <h3 class="text-lg font-medium">AI 小助手</h3>
        <CancelSvg width="28" height="28" style="margin-left: auto" />
      </div>
      <div class="message-container p-4" ref="messageContainer">
        <div
          v-for="(message, index) in messages"
          :key="index"
          class="flex items-start mb-4"
          :class="{ 'justify-end': message.isUser }"
        >
          <div
            v-if="message.isUser"
            class="bg-blue-100 text-blue-900 p-2 rounded-lg"
          >
            <p>{{ message.text }}</p>
          </div>
          <div v-if="!message.isUser">
            <DeepSeekIcon />
            <div class="bg-gray-100 text-gray-900 p-2 rounded-lg">
              <p>{{ message.text }}</p>
            </div>
          </div>
        </div>
      </div>
      <div class="border-t p-4 flex items-center">
        <input
          v-model="userInput"
          class="flex-grow p-2 border rounded-lg focus:outline-none"
          placeholder="输入你的问题..."
          type="text"
          @keydown.enter="sendMessage"
        />
        <div class="flex space-x-2 ml-2">
          <a-button @click="sendMessage">发送</a-button>
        </div>
      </div>
      <div class="text-center text-gray-400 text-sm p-2 mt-auto">
        deepseek提供支持，内容由 AI 生成，请仔细甄别
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
//todo :后续优化，在拖拽的过程中无法复制文字
import { ref, nextTick } from "vue";
import DeepSeekIcon from "@/components/admin/DeepSeekIcon.vue";
import CancelSvg from "@/components/admin/CancelSvg.vue";
import axios from "axios";

const userInput = ref("");
const messages = ref<{ text: string; isUser: boolean }[]>([]);
const messageContainer = ref<HTMLElement | null>(null);
const chatBox = ref<HTMLElement | null>(null);

let isDragging = false;
let offset = { x: 0, y: 0 };

const startDrag = (event: MouseEvent) => {
  isDragging = true;
  offset.x = event.clientX - (chatBox.value?.getBoundingClientRect().left || 0);
  offset.y = event.clientY - (chatBox.value?.getBoundingClientRect().top || 0);
};

const stopDrag = () => {
  isDragging = false;
};

const drag = (event: MouseEvent) => {
  if (isDragging && chatBox.value) {
    chatBox.value.style.position = "fixed";
    chatBox.value.style.left = `${event.clientX - offset.x}px`;
    chatBox.value.style.top = `${event.clientY - offset.y}px`;
  }
};

const sendMessage = async () => {
  if (userInput.value.trim()) {
    messages.value.push({ text: userInput.value.trim(), isUser: true });
    const question = userInput.value.trim();
    userInput.value = "";
    scrollToBottom();
    const resp = await axios.get("http://localhost:8101/api/deepseekAiSimple", {
      params: {
        input: question,
      },
    });
    const backendResponse = await resp.data;
    backendResponse.toString();
    // 模拟流式回答
    simulateBackendResponse(backendResponse);
  }
};

const scrollToBottom = () => {
  nextTick(() => {
    if (messageContainer.value) {
      messageContainer.value.scrollTop = messageContainer.value.scrollHeight;
    }
  });
};
// 模拟流式后端响应，逐字显示每句话
const simulateBackendResponse = (fullResponse: string) => {
  const sentences = fullResponse.split("。"); // 按句号分割
  let sentenceIndex = 0;
  const displayNextSentence = () => {
    if (sentenceIndex < sentences.length) {
      const sentence = sentences[sentenceIndex].trim();
      if (sentence) {
        let charIndex = 0;
        const charInterval = setInterval(() => {
          if (charIndex < sentence.length) {
            // 逐字显示
            const char = sentence.charAt(charIndex);
            if (charIndex === 0) {
              // 在句子开始时添加一条新消息
              messages.value.push({ text: "", isUser: false });
            }
            messages.value[messages.value.length - 1].text += char; // 更新最后一条消息
            scrollToBottom();
            charIndex++;
          } else {
            clearInterval(charInterval);
            sentenceIndex++;
            // 等待1秒再显示下一个句子
            setTimeout(displayNextSentence, 1000); // 1秒延迟
          }
        }, 50); // 每100毫秒添加一个字符
      } else {
        sentenceIndex++;
        displayNextSentence(); // 继续显示下一个句子
      }
    }
  };

  displayNextSentence(); // 开始显示第一个句子
};

// 监听鼠标移动事件
window.addEventListener("mousemove", drag);
window.addEventListener("mouseup", stopDrag);
</script>

<style scoped>
.chat-box {
  width: 500px; /* 固定宽度 */
  height: 600px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  position: fixed; /* 固定定位 */
  top: 200px; /* 距离顶部的距离 */
  right: 1300px; /* 距离右侧的距离 */
  z-index: 1000; /* 确保在最上层 */
  overflow-x: hidden; /* 防止水平滚动条出现 */
}

.header {
  cursor: move; /* 改变光标样式 */
}

.message-container {
  flex-grow: 1; /* 使消息区域占据剩余空间 */
  overflow-y: auto; /* 超出时出现垂直滚动条 */
  overflow-x: hidden; /* 防止水平滚动条出现 */
}

.flex {
  display: flex;
}

.justify-end {
  justify-content: flex-end;
}
</style>
